﻿using System;
using KinonekoSoftware.CodariaDB.Presets;
using KinonekoSoftware.Studio.Models.Shells;
using KinonekoSoftware.Foundation.UI.Media;

namespace KinonekoSoftware.Studio.Pages.Galleries
{
#if WINDOWS
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    
    public partial class NewInstanceViewModel
    {
        private string           _name;
        private string           _avatar;
        private ImageSource      _preview;
        private byte[]           _Buffer;

        public NewInstanceViewModel()
        {
            SelectAvatarCommand = new ActionCommand(SelectAvatarCommandHandler);
            ExtraTypes = new ObservableCollection<int>();
            Type = InstanceType.Character;
            Preview = Platform.GetDefaultImage();
        }

        private async void SelectAvatarCommandHandler()
        {
            var result = await Platform.Avatar();
            if (!result.IsFinished)
            {
                if(!string.IsNullOrEmpty(result.Reason)) await Danger(TitleSR.DangerOperation, result.Reason);
                return;
            }

            var r = result.Value;

            _Buffer = r.ImageBuffer;
            Preview = r.Image;
            Avatar = r.ImageID;
        }

        
        protected override void CreateValidationRules(ICollection<DialogRule> rules)
        {
            rules.Add(DialogRule.Create<NewInstanceViewModel>(SR.Parameter_Name, x => !string.IsNullOrEmpty(x.Name)));
        }
        
        protected override async Task<InstanceCache> OnFinish(bool editing)
        {
            InstanceCache instance;

            if (_useCustom)
            {
                instance = DataFactory.Create(_customType, _name);
            }
            else
            {
                instance = DataFactory.Create(_type, ExtraType, _name);
            }
            
            instance.Avatar = _avatar;
            
            if(!string.IsNullOrEmpty(instance.Avatar))
            {
                var gravatar = Platform.GetEngine<GravatarSystem>();
                
                //
                //
                await gravatar.WriteAsync(_avatar, _Buffer);
                gravatar.InsertOccupation(_avatar);

            }

            return instance;
        }


        
        
        public ImageSource Preview
        {
            get => _preview;
            set => SetValue(ref _preview, value);
        }

        
        public ICommandEX SelectAvatarCommand { get; }
    }
#endif
}